<template>
  <div>
    <Header :title="'返回'" :subTitle="'主题活动列表'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchList">
          <a-row :gutter="48">
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="有搭 ID">
                <a-input v-model="queryParam.lookId" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="主题搭配名称">
                <a-input v-model="queryParam.matchName" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="12" :xl="8" :lg="24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 18px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 18px" type="primary" icon="plus" @click="handleAdd">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs :activeKey="queryParam.status" @change="tabsChange">
        <a-tab-pane key="0" :tab="`上架（${running}）`"></a-tab-pane>
        <a-tab-pane key="1" :tab="`下架（${overdue}）`" forceRender></a-tab-pane>
      </a-tabs>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps">
        <span slot="matchingPicture" slot-scope="text">
          <img :src="thumb(text)" alt="" class="thumbnail" />
        </span>
        <span slot="marketingStatus" slot-scope="text">{{ text | marketingStatus }}</span>
        <span slot="createTime" slot-scope="text">{{ text | utc2beijing }}</span>
        <span slot="action" slot-scope="text, record" style="line-height:28px;">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <template v-if="queryParam.status == 1">
              <a-popconfirm title="确定删除该套主题搭配吗?" ok-text="确认" cancel-text="取消" @confirm="handleDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a-popconfirm title="确定上架架该套主题搭配吗?" ok-text="确认" cancel-text="取消" @confirm="confirmOffline(record)">
                <a href="javascript:;">上架</a>
              </a-popconfirm>
              <!-- <a @click="confirmOffline(record)">上架</a> -->
            </template>
            <template v-else>
              <a @click="getCode(record)">二维码</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定下架该套主题搭配吗?" ok-text="确认" cancel-text="取消" @confirm="confirmOffline(record)">
                <a href="javascript:;">下架</a>
              </a-popconfirm>
              <!-- <br />
              <a @click="upOrDown(record, 'up')"><a-icon type="arrow-up"/></a>
              <a-divider type="vertical" />
              <a @click="upOrDown(record, 'down')"><a-icon type="arrow-down"/></a> -->
            </template>
          </template>
        </span>
      </s-table>
    </a-card>
    <CodeModal ref="codeModal"></CodeModal>
  </div>
</template>
<script>
import { STable, Ellipsis } from '../../components'
import Header from '@/views/box/components/layouts/Header'
import CodeModal from './codeModal'
import { routeMixin } from '@/views/box/util/routeMixin'
import { themeMixin } from './util/mixin'
import { getThemeMatchList, onOrDownThemeMatchById, createThemeMatchQrCode, delThemeMatchById } from '@/api/box/theme'
const columns = [
  {
    title: '图片',
    dataIndex: 'matchingPicture',
    scopedSlots: { customRender: 'matchingPicture' }
  },
  {
    title: '主题搭配名称',
    dataIndex: 'matchName',
    align: 'center'
  },
  {
    title: '归属活动品牌',
    dataIndex: 'joinBrandName',
    align: 'center'
  },
  {
    title: '关联有搭 ID',
    dataIndex: 'lookId',
    align: 'center'
  },
  {
    title: '营销标识',
    dataIndex: 'marketingStatus',
    align: 'center',
    scopedSlots: { customRender: 'marketingStatus' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    scopedSlots: { customRender: 'createTime' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '250px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'success',
    text: '启用'
  }
}
export default {
  mixins: [routeMixin, themeMixin],
  components: {
    STable,
    Ellipsis,
    Header,
    CodeModal
  },
  data() {
    this.columns = columns
    return {
      thiemeId: '',
      // 查询参数
      queryParam: {
        status: '0'
      },
      overdue: '',
      running: '',
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      loadData: parameter => this.fetchList(parameter)
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
    marketingStatus(v) {
      switch (v) {
        case 0:
          return '无'
        case 1:
          return 'NEW'
        case 2:
          return 'HOT'
      }
    }
  },
  computed: {
    thumb(value) {
      return value => {
        if (value == null) return ''
        let arr = value.split(',')
        return arr[0]
      }
    }
  },
  watch: {
    $route(to, from) {
      if (to.path.includes('/box/operations/theme/lookDetail') && from.path.includes('/box/operations/theme/lookList')) {
        console.log('***1***')
      } else if (from.path.includes('/box/operations/theme/lookDetail') && to.path.includes('/box/operations/theme/lookList')) {
        console.log('***refresh LookList***')
        this.$refs.table.refresh()
      } else {
        console.log('******destroy LookList********')
        this.$destroy()
      }
    }
  },
  created() {
    this.initialPage()
  },
  methods: {
    // 初始化页面
    async initialPage() {
      // await this.fetchMaterialList()
      this.themeId = this.$route.params.themeId
    },
    headerBack() {
      this.$router.push('/box/operations/theme/list')
    },
    tabsChange(key) {
      this.queryParam.status = key
      this.$refs.table.refresh(true)
    },
    searchList() {
      this.$refs.table.refresh(true)
    },
    resetList() {
      this.queryParam.lookId = ''
      this.queryParam.matchName = ''
      this.$refs.table.refresh(true)
    },
    handleAdd() {
      this.$router.push(`/box/operations/theme/lookDetail/${this.themeId}/add`)
    },
    handleEdit(record) {
      this.$router.push(`/box/operations/theme/lookDetail/${this.themeId}/${record.id}`)
    },
    confirmOffline(record) {
      let params = {
        requestData: {
          id: record.id,
          status: record.status == 0 ? 1 : 0
        }
      }
      onOrDownThemeMatchById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功！')
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    getCode(record) {
      let params = {
        requestData: {
          themeMatchId: record.id
        }
      }
      createThemeMatchQrCode(params).then(res => {
        if (res.code == 0) {
          this.$refs.codeModal.show(res.data)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleDelete(record) {
      let params = {
        requestData: { id: record.id }
      }
      delThemeMatchById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('删除成功！')
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    fetchList(parameter) {
      let formValue = this.filterFields(this.queryParam)

      let params = {
        page: parameter,
        requestData: { activityId: this.themeId, ...formValue }
      }

      return getThemeMatchList(params).then(res => {
        if (res.code == 0) {
          this.running = res.data.up
          this.overdue = res.data.down
          return {
            page: res.page,
            data: res.data.data
          }
        } else {
          this.$message.warning(res.msg)
          const data = {
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            },
            data: []
          }
          return data
        }
      })
    },
    filterFields(values) {
      let formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] != '' && values[i] != undefined) {
          formValue[i] = values[i].trim()
        }
      })
      return formValue
    }
  }
}
</script>
<style lang="less" scoped>
.thumbnail {
  height: 80px;
  margin-right: 12px;
  border: 1px dashed #cdcdcd;
  width: 80px;
  object-fit: scale-down;
  background: #fff;
  cursor: pointer;
}
</style>

